package com.wnxy.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wnxy.admin.common.handler.Asserts;
import com.wnxy.admin.common.handler.BusinessEnum;
import com.wnxy.admin.entity.Role;
import com.wnxy.admin.entity.RolePermission;
import com.wnxy.admin.entity.Staff;
import com.wnxy.admin.entity.StaffRole;
import com.wnxy.admin.mapper.RoleMapper;
import com.wnxy.admin.mapper.RolePermissionMapper;
import com.wnxy.admin.mapper.StaffMapper;
import com.wnxy.admin.mapper.StaffRoleMapper;
import com.wnxy.admin.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author All
 * @since 2023-11-29
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    private final RoleMapper roleMapper;
    private final StaffRoleMapper staffRoleMapper;

    private final RolePermissionMapper rolePermissionMapper;

    public RoleServiceImpl(RoleMapper roleMapper, StaffMapper staffMapper, StaffRoleMapper staffRoleMapper, RolePermissionMapper rolePermissionMapper) {
        this.roleMapper = roleMapper;
        this.staffRoleMapper = staffRoleMapper;
        this.rolePermissionMapper = rolePermissionMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(Role role) {
        //校验角色是否存在
        boolean flag = roleMapper.exists(Wrappers.lambdaQuery(Role.class).eq(Role::getRoleName, role.getRoleName()));
        Asserts.fail(flag == true, BusinessEnum.ROLE_EXISTS);
        flag = roleMapper.exists(Wrappers.lambdaQuery(Role.class).eq(Role::getRoleCode, role.getRoleCode()));
        Asserts.fail(flag == true, BusinessEnum.ROLE_EXISTS);
        //
        roleMapper.insert(role);
    }

    @Override
    public PageInfo<Staff> getAll(Integer pageNum, Integer pageSize, String keyword) {
        PageHelper.startPage(pageNum, pageSize);
        List<Staff> staffs = roleMapper.selectAll(keyword);
        return new PageInfo<>(staffs);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteRole(Integer id) {
        //用户角色表
        staffRoleMapper.delete(Wrappers.lambdaQuery(StaffRole.class)
                .eq(StaffRole::getRoleId,id));
        //角色权限
        rolePermissionMapper.delete(Wrappers.lambdaQuery(RolePermission.class)
                .eq(RolePermission::getRoleId,id));
        //自己
        roleMapper.deleteById(id);
    }
}
